import utils from './utils'
// 此vm参数为页面的实例，可以通过它引用vuex中的变量
module.exports = (vm) => {
	// 初始化请求配置
	uni.$u.http.setConfig((config) => {
		config.baseURL = utils.baseURL;
		// config.header['Content-Type'] = 'application/x-www-form-urlencoded'
		// config.header["X-Requested-With"] = "XMLHttpRequest"
		return config
	})

	// 请求拦截
	uni.$u.http.interceptors.request.use((config) => {
		config.data = config.data || {}
		let token = uni.getStorageSync('token')
		// if(!token){
		// 	uni.reLaunch({
		// 		url:"/pages/login/index"
		// 	})
		// }
		if (token) {
			config.header['X-Access-Token'] = token
		}
		return config
	}, config => {
		return Promise.reject(config)
	})
	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => {
		if(response.data.code === 3014 ) {
			uni.showModal({
				title:"系统提示！",
				content:response.data.message
			})
			return Promise.reject(response.data.message || '登录失效')
		}
		if (response.data.code === 401 || response.data.code === 401) {
			// 登录失效
			let pages = getCurrentPages();
			// console.log(pages)
			// let forward = pages && pages[pages.length - 1] ? pages[pages.length - 1]['$page'] : null;
			// uni.setStorageSync('forward', JSON.stringify(forward));
			// uni.removeStorageSync('userInfo');
			uni.removeStorageSync('token');
			uni.$u.route({
				type: 'redirect',
				url: '/pages/login/index'
			});
			return Promise.reject(response.data.message || '登录失效')
		}


		if (response.data.code === 200) {
			// console.log(response.data.code)
			// var result = response.data;
			if (response.data.code !== 200) {
				
				uni.$u.toast(response.data.message || '请求异常~')
				uni.removeStorageSync('token');
				uni.$u.route({
					type: 'redirect',
					url: '/pages/login/index'
				});
				return Promise.reject(response.data.message)
			}
			else
			{
				// result['err']
				if(response.data.result?.errorMsg)
				uni.$u.toast(response.data.result.errorMsg )
			}
			return response.data === undefined ? {} : response.data
		} else {
			uni.$u.toast(response.data.message || '请求异常~')
			return Promise.reject(response)
		}
	}, (response) => {
		if (response.data.code == 401) {
			uni.$u.toast(response.data.message || '请求异常~')
			uni.removeStorageSync('token');
			uni.$u.route({
				type: 'redirect',
				url: '/pages/login/index'
			});
		}else{
			uni.$u.toast(response.data.message || '请求异常~')
		}
		return Promise.reject(response)
	})
}
